﻿using System;
using System.Reflection;
using UnityEngine;

namespace TC
{
    public class FlowInput<T> : FlowPort
    {
        public override Type type => typeof(T);
        public override bool IsInput => true;
        public override bool AllowMultiConnect => true;

        public FlowInput(FlowNode parent, string name) : base(parent, name)
        {
        }

        public override bool CanConnect(Port other)
        {
            if (other is FlowPort && !other.IsInput 
                && other.parent.GetType().IsSubclassOf(type)
                && parent.GetType().IsSubclassOf(other.type))
            {
                return true;
            }
            return false;
        }

        public override bool CanConnect(Type nodeType, out FieldInfo portInfo)
        {
            var fields = nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (var field in fields)
            {
                if (field.FieldType.IsGenericType)
                {
                    Type generic = field.FieldType.GetGenericArguments()[0];
                    var targetType = typeof(FlowOutput<>).MakeGenericType(generic);
                    if (field.FieldType == targetType)
                    {
                        if (typeof(T).IsAssignableFrom(nodeType)
                            && generic.IsAssignableFrom(parent.GetType()))
                        {
                            portInfo = field;
                            return true;
                        }
                    }
                }
            }
            portInfo = default;
            return false;
        }
    }
}
